/**
 * @authors YaoRen (hongjiawei@uworks.cc)
 * @date    2016-10-17 11:24:55
 */

var userType; //用户类型（1：普通用户，2：渠道用户）

// 登录对话窗
var dialog_login = dialog({
    id: 'dialog_login',
    title: '<img src="../images/ui-dialog-logo.jpg">',
    content: '<div id="dialog-login" class="ui-dialog-login">' +
        '<ul class="ui-form">' +
            '<li class="ui-form-item">' +
                '<input id="code-login-mobile" class="ui-input" type="text" placeholder="手机号" maxlength="11">' +
            '</li>' +
            '<li id="j-login-verify" class="ui-form-item ui-verify ui-flex">' +
                '<input id="code-login-verify" class="ui-input ui-flex-item" type="text" value="" placeholder="验证码"><a href="javascript:void(0);" id="btn-login-verify" class="ui-btn-verify disabled" data-verify-status="1">获取验证码</a>' +
            '</li>' +
            '<li id="j-login-password" class="ui-form-item hidden">' +
                '<input id="code-login-password" class="ui-input" type="password" value="" placeholder="登录密码">' +
            '</li>' +
            '<li class="ui-form-item clearfix">' +
                '<a href="javascript:;" id="j-login-type" class="ui-link fl" data-login-type="1">使用密码登录</a>' +
                '<a href="javascript:;" class="j-user-retrieve ui-link fr">忘记密码</a>' +
            '</li>' +
        '</ul>' +
        '<div class="login-bot">' +
            '<a href="javascript:;" class="j-user-register ui-link">还有没账号？立即注册</a>' +
            '<p class="explain">注册账号并与联创工场达成合作后,您可以实时监控您的项目质量和进度</p>' +
        '</div>' +
        '<div class="ui-dialog-alert"></div>' +
    '</div>',
    okValue: '登录',
    ok: function () {
        // 用户登录请求操作
        uworksLogin(function() {
            dialog_login.close();
        });
        return false;
    },
    cancel: function () {
        this.close();
        return false;
    },
    cancelDisplay: false
});

// 注册对话窗
var dialog_register = dialog({
    id: 'dialog_register',
    title: '<img src="../images/ui-dialog-logo.jpg">',
    content: '<div id="dialog-register" class="ui-dialog-login">' +
        '<ul class="ui-form">' +
            '<li class="ui-form-item">' +
                '<input id="code-register-mobile" class="ui-input" type="text" value="" placeholder="手机号" maxlength="11">' +
            '</li>' +
            '<li class="ui-form-item ui-verify ui-flex">' +
                '<input id="code-register-verify" class="ui-input ui-flex-item" type="text" value="" placeholder="验证码"><a href="javascript:void(0);" id="btn-register-verify" class="ui-btn-verify disabled" data-verify-status="1">获取验证码</a>' +
            '</li>' +
            '<li class="ui-form-item">' +
                '<input id="code-register-password" class="ui-input" type="password" value="" placeholder="设置新密码8-16字符" maxlength="16">' +
            '</li>' +
        '</ul>' +
        '<div class="login-bot">' +
            '<a href="javascript:;" class="j-user-login j-switch-login ui-link">已有账号？立即登录</a>' +
            '<p class="explain">注册账号并与联创工场达成合作后,您可以实时监控您的项目质量和进度</p>' +
        '</div>' +
        '<div class="ui-dialog-alert"></div>' +
    '</div>',
    okValue: '注册',
    ok: function () {
        // 用户注册请求操作
        uworksRegister(function() {
            dialog_register.close();
        });
        return false;
    },
    cancel: function () {
        this.close();
        return false;
    },
    cancelDisplay: false
});

// 找回密码对话窗
var dialog_retrieve = dialog({
    id: 'dialog_retrieve',
    title: '<img src="../images/ui-dialog-logo.jpg">',
    content: '<div id="dialog-retrieve" class="ui-dialog-login">' +
        '<ul class="ui-form">' +
            '<li class="ui-form-item">' +
                '<input id="code-retrieve-mobile" class="ui-input" type="text" value="" placeholder="手机号" maxlength="11">' +
            '</li>' +
            '<li class="ui-form-item ui-verify ui-flex">' +
                '<input id="code-retrieve-verify" class="ui-input ui-flex-item" type="text" value="" placeholder="验证码"><a href="javascript:void(0);" id="btn-retrieve-verify" class="ui-btn-verify disabled" data-verify-status="1">获取验证码</a>' +
            '</li>' +
            '<li class="ui-form-item">' +
                '<input id="code-retrieve-password" class="ui-input" type="password" value="" placeholder="设置新密码8-16字符" maxlength="16">' +
            '</li>' +
        '</ul>' +
        '<div class="login-bot">' +
            '<a href="javascript:;" class="j-user-login j-switch-login ui-link">记起密码了？立即登录</a>' +
        '</div>' +
        '<div class="ui-dialog-alert"></div>' +
    '</div>',
    okValue: '保存密码',
    ok: function () {
        // 用户找回密码请求操作
        uworksRetrieve(function() {
            dialog_retrieve.close();
        });
        return false;
    },
    cancel: function () {
        this.close();
        return false;
    },
    cancelDisplay: false
});

// 对话窗初始化
function dialogInit(){
    // 登录对话窗唤起
    $('.j-user-login').off('click').on('click', function(){
        var _this = $(this);
        userType = _this.attr('data-user-type');
        userName = _this.attr('data-user');
        $('.j-switch-login').attr('data-user-type', userType);
        if(userType == 1){  //普通用户
            $('div[aria-labelledby="title:dialog_login"]').find('button[i-id="ok"]').text('用户登录');
            if(_this.attr('data-nav') == 'project'){
                if(userName){
                    window.location.href = '/my_project.html?title=project';
                    return false;
                }else{
                    sessionStorage.target_url = '/my_project.html?title=project';
                }
            }
        }else if(userType ==2){  //渠道商用户
            $('div[aria-labelledby="title:dialog_login"]').find('button[i-id="ok"]').text('渠道商登录');
            if(userName){
                window.location.href = '/channel_statistics.html';
                return false;
            }
        }
        dialog_register.close();
        dialog_retrieve.close();
        dialog_login.showModal();
        document.onkeydown = function(event) {
            var e = event || window.event || arguments.callee.caller.arguments[0];
            if(e && e.keyCode == 13) { // enter 键
                 dialog_login._trigger('ok');
            }
        };
    });

    // 注册对话窗唤起
    $('.j-user-register').off('click').on('click', function(){
        var _this = $(this);
        if (_this.attr('data-user-type')) {
            userType = _this.attr('data-user-type');
            $('.j-switch-login').attr('data-user-type', userType);
        }
        if(userType == 1){  //普通用户
            $('div[aria-labelledby="title:dialog_register"]').find('button[i-id="ok"]').text('用户注册');
        }else if(userType == 2){  //渠道商用户
            $('div[aria-labelledby="title:dialog_register"]').find('button[i-id="ok"]').text('渠道商注册');
        }
        dialog_login.close();
        dialog_retrieve.close();
        dialog_register.showModal();
        document.onkeydown = function(event) {
            var e = event || window.event || arguments.callee.caller.arguments[0];
            if(e && e.keyCode == 13) { // enter 键
                 dialog_register._trigger('ok');
            }
        };
    });

    // 找回密码对话窗唤起
    $('.j-user-retrieve').off('click').on('click', function(){
        dialog_login.close();
        dialog_register.close();
        dialog_retrieve.showModal();
        document.onkeydown = function(event) {
            var e = event || window.event || arguments.callee.caller.arguments[0];
            if(e && e.keyCode == 13) { // enter 键
                 dialog_retrieve._trigger('ok');
            }
        };
    });

    // 登录方式切换
    $('#j-login-type').off('click').on('click', function(){
        var _this = $(this);
        var loginType = _this.attr('data-login-type');
        // 登录方式状态判断（1：验证码登录，2：密码登录）
        if(loginType == 1){
            $('#j-login-password').removeClass('hidden');
            $('#j-login-verify').addClass('hidden');
            _this.html('使用验证码登录').attr('data-login-type', 2);
        }else if(loginType == 2){
            $('#j-login-verify').removeClass('hidden');
            $('#j-login-password').addClass('hidden');
            _this.html('使用密码登录').attr('data-login-type', 1);
        }
    });
}

// 对话窗提示
function dialogAlert(elem, str){
    var _this = $(elem),
        _thisAlert = _this.find('.ui-dialog-alert');

    countTime = 0;
    if(_this !== 'undefined' || _thisAlert !== 'undefined'){
        if(!_thisAlert.hasClass('show')){
            countdown();
        }
        _thisAlert.html(str).addClass('show').slideDown(300);
        function countdown(){
            countTime++;
            if(countTime >= 5){
                _thisAlert.removeClass('show').slideUp(300);
            }else{
                setTimeout(countdown, 1000);
            }
        }
    }
}

// 验证码倒计时
function setCountDown(elem) {
    var _this = $(elem),
        countTime = 60;
    var countdown = setInterval(function() {
        if(countTime > 0) {
            countTime--;
            _this.html('已发送（' + countTime + 's）').attr('data-verify-status', 0).addClass('disabled');;
        }else {
            _this.html('重新发送').attr('data-verify-status', 1).removeClass('disabled');
            clearInterval(countdown);
        }
    },1000);
}

// 用户登录请求操作
function uworksLogin(success){
    var mobile,     //登录手机号
        password,   //登录密码
        loginType,  //登录方式（1：验证码登录，2：密码登录）
        requestUrl; //接口请求地址

    mobile = $.trim($('#code-login-mobile').val());
    loginType = $('#j-login-type').attr('data-login-type');

    if(!mobile){
        dialogAlert('#dialog-login', '请输入手机号');
        $('#code-login-mobile').focus();
        return false;
    }
    if(!matchMobile(mobile)){
        dialogAlert('#dialog-login', '请输入正确手机号');
        $('#code-login-mobile').focus();
        return false;
    }

    if(loginType == 1){    //验证码登录
        password = $.trim($('#code-login-verify').val());
        if(password == ''){
            dialogAlert('#dialog-login', '请输入验证码');
            $('#code-login-verify').focus();
            return false;
        }
    }else if(loginType == 2){   //密码登录
        password = $.trim($('#code-login-password').val());
        if(!password){
            dialogAlert('#dialog-login', '请输入密码');
            $('#code-login-password').focus();
            return false;
        }
        if(!matchPassword(password)){
            dialogAlert('#dialog-login', '请输入8-16位字符密码');
            $('#code-login-password').focus();
            return false;
        }
    }

    if(userType == 1){    //普通用户
        requestUrl= '/user/login';
    }else if(userType == 2){    //渠道用户
        requestUrl= '/channel/user/login';
    }

    $.ajax({
        url: host + requestUrl,
        type: "post",
        dataType: "json",
        xhrFields: {
            withCredentials: true
        },
        beforeSend: function(xhr) {
            xhr.setRequestHeader("Content-Type", "application/json");
        },
        data: JSON.stringify({
            "tel": mobile,
            "password": password
        }),
        complete: function(respResult) {
            if(respResult.status == 200) {
                if (typeof(success) != 'undefined') {
                    success();
                }

                if(userType == 1) {   // 普通用户
                    $('#myProject').data("tel", mobile);
                    $('#myProject-mp').data("tel", mobile);
                    if(sessionStorage.target_url) {
                        window.location.href = sessionStorage.target_url;
                        sessionStorage.removeItem('target_url');
                    } else if(sessionStorage.message_roles_url || sessionStorage.project_model_url) {
                        save();
                        sessionStorage.removeItem('message_roles_url')
                        sessionStorage.removeItem('project_model_url');
                    } else {
                        window.location.reload();
                    }
                }else if(userType == 2) {   //渠道商用户
                    window.location.href = '/channel_statistics.html';
                }
            }else {
                dialogAlert('#dialog-login', JSON.parse(respResult.responseText).message);
            }
        }
    });
}

// 用户注册请求操作
function uworksRegister(success){
    var mobile,     //注册手机号
        verifycode, //注册验证码
        password,   //注册密码
        requestUrl; //接口请求地址

    mobile = $.trim($('#code-register-mobile').val());
    verifycode = $.trim($('#code-register-verify').val());
    password = $.trim($('#code-register-password').val());

    if(!mobile){
        dialogAlert('#dialog-register', '请输入手机号');
        $('#code-register-mobile').focus();
        return false;
    }
    if(!matchMobile(mobile)){
        dialogAlert('#dialog-register', '请输入正确手机号');
        $('#code-register-mobile').focus();
        return false;
    }
    if(verifycode == ''){
        dialogAlert('#dialog-register', '请输入验证码');
        $('#code-register-verify').focus();
        return false;
    }
    if(!password){
        dialogAlert('#dialog-register', '请输入密码');
        $('#code-register-password').focus();
        return false;
    }
    if(!matchPassword(password)){
        dialogAlert('#dialog-register', '请输入8-16位字符密码');
        $('#code-register-password').focus();
        return false;
    }

    if(userType == 1){    //普通用户
        requestUrl= '/user/findPwd';
    }else if(userType == 2){    //渠道用户
        requestUrl= '/channel/user/findPwd';
    }

    $.ajax({
        url: host + requestUrl,
        type: "post",
        dataType: "json",
        xhrFields: {
            withCredentials: true
        },
        beforeSend: function(xhr) {
            xhr.setRequestHeader("Content-Type", "application/json");
        },
        data: JSON.stringify({
            "tel": mobile,
            "code": verifycode,
            "password": password
        }),
        complete: function(respResult) {
            if(respResult.status == 200) {
                if (typeof(success) != 'undefined') {
                    success();
                }
            }else {
                dialogAlert('#dialog-register', JSON.parse(respResult.responseText).message);
            }
        }
    });
}

// 用户找回密码请求操作
function uworksRetrieve(success){
    var mobile,     //找回密码手机号
        verifycode, //找回密码验证码
        password,   //找回密码密码
        requestUrl; //接口请求地址

    mobile = $.trim($('#code-retrieve-mobile').val());
    verifycode = $.trim($('#code-retrieve-verify').val());
    password = $.trim($('#code-retrieve-password').val());

    if(!mobile){
        dialogAlert('#dialog-retrieve', '请输入手机号');
        $('#code-retrieve-mobile').focus();
        return false;
    }
    if(!matchMobile(mobile)){
        dialogAlert('#dialog-retrieve', '请输入正确手机号');
        $('#code-retrieve-mobile').focus();
        return false;
    }
    if(verifycode == ''){
        dialogAlert('#dialog-retrieve', '请输入验证码');
        $('#code-retrieve-verify').focus();
        return false;
    }
    if(!password){
        dialogAlert('#dialog-retrieve', '请输入密码');
        $('#code-retrieve-password').focus();
        return false;
    }
    if(!matchPassword(password)){
        dialogAlert('#dialog-retrieve', '请输入8-16位字符密码');
        $('#code-retrieve-password').focus();
        return false;
    }

    if(userType == 1){    //普通用户
        requestUrl= '/user/retrieve';
    }else if(userType == 2){    //渠道用户
        requestUrl= '/channel/user/retrieve';
    }

    $.ajax({
        url: host + requestUrl,
        type: "post",
        dataType: "json",
        xhrFields: {
            withCredentials: true
        },
        beforeSend: function(xhr) {
            xhr.setRequestHeader("Content-Type", "application/json");
        },
        data: JSON.stringify({
            "tel": mobile,
            "code": verifycode,
            "password": password
        }),
        complete: function(respResult) {
            if(respResult.status == 200) {
                if (typeof(success) != 'undefined') {
                    success();
                }
            }else {
                dialogAlert('#dialog-retrieve', JSON.parse(respResult.responseText).message);
            }
        }
    });
}

// 验证码操作初始化
function verifyCodeInit() {
    // 监听登录手机号输入框
    $("#code-login-mobile").on('input focus click blur change', function() {
        var mobile = $.trim($(this).val()), //手机号
            verifyStatus = $('#btn-login-verify').attr('data-verify-status'); //验证码发送状态（0：已发送，1：未发送）

        if(matchMobile(mobile) && verifyStatus == 1) {
            $('#btn-login-verify').removeClass('disabled');
        }else {
            $('#btn-login-verify').addClass('disabled');
        }
    });

    // 监听注册手机号输入框
    $("#code-register-mobile").on('input focus click blur change', function() {
        var mobile = $.trim($(this).val()), //手机号
            verifyStatus = $('#btn-register-verify').attr('data-verify-status'); //验证码发送状态（0：已发送，1：未发送）

        if(matchMobile(mobile) && verifyStatus == 1) {
            $('#btn-register-verify').removeClass('disabled');
        }else {
            $('#btn-register-verify').addClass('disabled');
        }
    });

    // 监听找回密码手机号输入框
    $("#code-retrieve-mobile").on('input focus click blur change', function() {
        var mobile = $.trim($(this).val()), //手机号
            verifyStatus = $('#btn-retrieve-verify').attr('data-verify-status'); //验证码发送状态（0：已发送，1：未发送）

        if(matchMobile(mobile) && verifyStatus == 1) {
            $('#btn-retrieve-verify').removeClass('disabled');
        }else {
            $('#btn-retrieve-verify').addClass('disabled');
        }
    });

    // 用户登录验证码
    $('#btn-login-verify').on('click', function() {
        var _this = $(this),
            verifyStatus = _this.attr('data-verify-status'), //验证码发送状态（0：已发送，1：未发送）
            mobile,     //登录手机号
            requestUrl; //接口请求地址

        if(verifyStatus == 1) {
            _this.html('正在发送').addClass('disabled').attr('data-verify-status', 0);

            mobile = $.trim($('#code-login-mobile').val());

            if(userType == 1) {   // 普通用户
                requestUrl = '/msg/login/user';
            }else if(userType == 2) {   //渠道商用户
                if(matchMobile(mobile)){
                    requestUrl = '/msg/login/channel';
                }else if(isEmail(mobile)){
                    requestUrl = '/msg/login/channel/email';
                }
            }

            $.ajax({
                url: host + requestUrl,
                type: "post",
                dataType: "json",
                xhrFields: {
                    withCredentials: true
                },
                data:JSON.stringify({
                    "tel": mobile
                }),
                beforeSend: function (xhr) {
                    xhr.setRequestHeader("Content-Type", "application/json");
                },
                complete: function (respResult) {
                    if (respResult.status == 200) {
                        setCountDown('#btn-login-verify');
                    } else {
                        dialogAlert('#dialog-login', JSON.parse(respResult.responseText).message);
                        _this.html('获取验证码').removeClass('disabled').attr('data-verify-status', 1);
                    }
                }
            });
        }
    });

    // 用户注册验证码
    $('#btn-register-verify').on('click', function() {
        var _this = $(this),
            verifyStatus = _this.attr('data-verify-status'), //验证码发送状态（0：已发送，1：未发送）
            mobile,     //注册手机号
            requestUrl; //接口请求地址

        if(verifyStatus == 1) {
            _this.html('正在发送').addClass('disabled').attr('data-verify-status', 0);

            mobile = $.trim($('#code-register-mobile').val());

            if(userType == 1) {   // 普通用户
                requestUrl = '/msg/register';
            }else if(userType == 2) {   //渠道商用户
                requestUrl = '/msg/register/channel';
            }

            $.ajax({
                url: host + requestUrl,
                type: "post",
                dataType: "json",
                xhrFields: {
                    withCredentials: true
                },
                data:JSON.stringify({
                    "tel": mobile
                }),
                beforeSend: function (xhr) {
                    xhr.setRequestHeader("Content-Type", "application/json");
                },
                complete: function (respResult) {
                    if (respResult.status == 200) {
                        setCountDown('#btn-register-verify');
                    } else {
                        dialogAlert('#dialog-register', JSON.parse(respResult.responseText).message);
                        _this.html('获取验证码').removeClass('disabled').attr('data-verify-status', 1);
                    }
                }
            });
        }
    });

    // 用户找回密码验证码
    $('#btn-retrieve-verify').on('click', function() {
        var _this = $(this),
            verifyStatus = _this.attr('data-verify-status'), //验证码发送状态（0：已发送，1：未发送）
            mobile,     //找回密码手机号
            requestUrl; //接口请求地址

        if(verifyStatus == 1) {
            _this.html('正在发送').addClass('disabled').attr('data-verify-status', 0);

            mobile = $.trim($('#code-retrieve-mobile').val());

            if(userType == 1) {   // 普通用户
                requestUrl = '/msg/findPwd';
            }else if(userType == 2) {   //渠道商用户
                requestUrl = '/msg/findPwd/channel';
            }

            $.ajax({
                url: host + requestUrl,
                type: "post",
                dataType: "json",
                xhrFields: {
                    withCredentials: true
                },
                data:JSON.stringify({
                    "tel": mobile
                }),
                beforeSend: function (xhr) {
                    xhr.setRequestHeader("Content-Type", "application/json");
                },
                complete: function (respResult) {
                    if (respResult.status == 200) {
                        setCountDown('#btn-retrieve-verify');
                    } else {
                        dialogAlert('#dialog-retrieve', JSON.parse(respResult.responseText).message);
                        _this.html('获取验证码').removeClass('disabled').attr('data-verify-status', 1);
                    }
                }
            });
        }
    });
}


/*用户登录情况下title右上角显示功能模块的点击事件*/
//点击显示功能模块
function clickShowRightContent(){
    $("#userOpt .click-show-info").on("click",function(e){
        e.stopPropagation();
        $(".pullDown-menu").toggle();
    });
    $("body").on("click",function(){
        $(".pullDown-menu").hide();
    });
}

//绑定投诉按钮
function bindComplaintsBtn(){
    $("#complaints-btn").off("click").on("click",function(){
        var d = dialog({
            title: '<img src="../images/ui-dialog-logo.jpg"><span>我要投诉</span>',
            content: '<div class="ui-dialog-form">' +
                '<ul class="ui-form">' +
                    '<li class="ui-form-item">' +
                        '<div class="item-label">项目：</div>' +
                        '<div class="item-main">' +
                            '<div class="ui-select clearfix j-select" id="j-select-project">' +
                                '<div class="ui-select-view">' +
                                    '<input type="hidden" class="ui-select-value" value="">' +
                                    '<span class="ui-select-text" title=""><em class="ui-select-placeholder">请选择项目</em></span>' +
                                    '<div class="ui-select-icon"><i class="ui-select-icon-arrow"></i></div>' +
                                '</div>' +
                                '<ul class="ui-select-options">' +
                                '</ul>' +
                            '</div>' +
                        '</div>' +
                    '</li>' +
                    '<li class="ui-form-item">' +
                        '<div class="item-label">事由：</div>' +
                        '<div class="item-main">' +
                            '<div class="ui-select clearfix j-select" id="j-select-incident">' +
                                '<div class="ui-select-view">' +
                                    '<input type="hidden" class="ui-select-value" value="">' +
                                    '<span class="ui-select-text" title=""><em class="ui-select-placeholder">请选择事由</em></span>' +
                                    '<div class="ui-select-icon"><i class="ui-select-icon-arrow"></i></div>' +
                                '</div>' +
                                '<ul class="ui-select-options">' +
                                    '<li data-value="2">工作任务太慢</li>' +
                                    '<li data-value="3">工作态度不好</li>' +
                                    '<li data-value="4">工作质量不高</li>' +
                                    '<li data-value="5">其他</li>' +
                                '</ul>' +
                            '</div>' +
                        '</div>' +
                    '</li>' +
                    '<li class="ui-form-item">' +
                        '<div class="item-label">投诉内容：</div>' +
                        '<div class="item-main">' +
                            '<textarea id="content-complaints" class="ui-textarea" rows="6" placeholder="请详细描述您在工作中遇到的问题（人物 时间 任务）"></textarea>' +
                        '</div>' +
                    '</li>' +
                '</ul>' +
            '</div>',
            okValue: '提交',
            ok: function () {
                var params = {};
                params.projectId = parseInt($("#j-select-project input").val());
                params.type = parseInt($("#j-select-incident input").val());
                params.content = $.trim($("#content-complaints").val());
                if (params.projectId == '') {
                    alertReturn("请选择投诉项目！");
                    return false;
                }
                if (params.type == '') {
                    alertReturn("请选择投诉事由！");
                    return false;
                }
                if (params.content == '') {
                    alertReturn("请填写投诉内容！");
                    return false;
                }
                $.ajax({
                    url: host + "/complaint/submit",
                    type: "post",
                    dataType: "json",
                    xhrFields: {
                        withCredentials: true
                    },
                    data:JSON.stringify(params),
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("Content-Type", "application/json");
                    },
                    success: function (data) {
                        d.close().remove();
                        var d2 = dialog({
                            content: '<div class="ui-dialog-success">' +
                                '<div class="icon-success"><img src="/module/images/tick.png"></div>' +
                                '<p>您的投诉uworks已知悉<br>会尽快沟通处理！</p>' +
                            '</div>',
                            okValue: '确定',
                            ok: function () {}
                        });
                        d2.showModal();
                    }
                });
                return false;
            },
            cancelValue: '取消',
            cancel: function () {}
        });
        d.showModal();

        tProjectList();
    });
}

//投诉项目列表
function tProjectList() {
    $.ajax({
        url: host + "/project/list",
        type: "get",
        dataType: "json",
        xhrFields: {
            withCredentials: true // 确保请求会携带上Cookie
        },
        beforeSend: function (xhr) {
            xhr.setRequestHeader("Content-Type", "application/json"); // 设置请求协议，会触发PreFlight
        },
        success: function (respResult) {
            if (respResult.length > 0) {
                var projectStr ='';
                for (var i = 0; i < respResult.length; i++) {
                    projectStr += "<li data-value='" + respResult[i].id + "'>" + respResult[i].projectName + "</li>";
                }
                $("#j-select-project .ui-select-options").html(projectStr);

                $(".j-select").each(function(){
                    $(this).jSelect();  //下拉选择
                });
            }
        },
        error: function (respResult) {

        }
    });
}


/*** 顶部退出按钮*/
function clickRightExit(){
    $("#j-user-logout").on("click", function () {
        var d = dialog({
            content: '<div class="ui-dialog-text">您确定要退出登录吗？</div>',
            okValue: '确定',
            ok: function () {
                $.ajax({
                    url: host + "/user/logout",
                    type: "post",
                    dataType: "json",
                    xhrFields: {
                        withCredentials: true // 确保请求会携带上Cookie
                    },
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("Content-Type", "application/json"); // 设置请求协议，会触发PreFlight
                    },
                    complete:function(){
                        sessionStorage.removeItem('demandModuleItems');
                        sessionStorage.removeItem('demandModuleItemsFirst');
                        sessionStorage.removeItem('demandModuleItemsSecond');
                        sessionStorage.removeItem('five_to_one');
                        sessionStorage.removeItem('save');
                        sessionStorage.removeItem('project_form');//清空key为project_form存储的所有信息
                        sessionStorage.removeItem('id');//清空key为id存储的所有信息
                        window.location.href = "/index.html";
                    }
                });
            },
            cancelValue: '取消',
            cancel: function () {}
        });
        d.showModal();
    });
}

/*** 获取是否有消息提示*/
function getListCommentsNotRead(){
    $.ajax({
        url: host + "/ux/resource/comment/listCommentsNotRead",
        type: "get",
        dataType: "json",
        xhrFields: {
            withCredentials: true
        },
        beforeSend: function (xhr) {
            xhr.setRequestHeader("Content-Type", "application/json");
        },
        success: function (data) {
            var bean = data.beans;
            if (bean.length > 0) {
                $("#xxtx").addClass("xxtx");
            } else {
                $("#xxtx").removeClass("xxtx");
            }
        }
    });
}

/*** 顶部更改用户信息按钮*/
function updateMyselfInfo(){
    $("#user_tel").on("click", function () {
        var d = dialog({
            title: '<img src="../images/ui-dialog-logo.jpg"><span>个人信息设置</span>',
            content: '<div class="ui-dialog-form">' +
                '<ul class="ui-form">' +
                    '<li class="ui-form-item">' +
                        '<div class="item-label">电话号码：</div>' +
                        '<div class="item-main">' +
                            '<input id="client_tel" class="ui-input" type="text" value="" placeholder="请填写电话号码">' +
                        '</div>' +
                    '</li>' +
                    '<li class="ui-form-item">' +
                        '<div class="item-label">用户姓名：</div>' +
                        '<div class="item-main">' +
                            '<input id="client_name" class="ui-input" type="text" value="" placeholder="请填写用户姓名">' +
                        '</div>' +
                    '</li>' +
                    '<li class="ui-form-item">' +
                        '<div class="item-label">邮箱号码：</div>' +
                        '<div class="item-main">' +
                            '<input id="client_email" class="ui-input" type="text" value="" placeholder="请填写邮箱号码">' +
                        '</div>' +
                    '</li>' +
                    '<li class="ui-form-item">' +
                        '<div class="item-label">公司名称：</div>' +
                        '<div class="item-main">' +
                            '<input id="client_company" class="ui-input" type="text" value="" placeholder="请填写公司名称">' +
                        '</div>' +
                    '</li>' +
                '</ul>' +
            '</div>',
            okValue: '保存',
            ok: function () {
                var name = $.trim($("#client_name").val());
                var email = $.trim($("#client_email").val());
                var company = $.trim($("#client_company").val());
                if (name.length != 0 && (name.length > 20 || name.length < 2)) {
                    alertReturn("您输入的用户姓名只能是2-20个字符！");
                    return false;
                }
                if (!isEmail(email) && email) {
                    alertReturn("您输入的邮箱格式不正确！");
                    return false;
                }
                if ($.trim(company)=="") {
                    alertReturn("公司名不能为空！");
                    return false;
                }
                $.ajax({
                    url: host + "/user/editName",
                    type: "post",
                    dataType: "json",
                    xhrFields: {
                        withCredentials: true // 确保请求会携带上Cookie
                    },
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("Content-Type", "application/json"); // 设置请求协议，会触发PreFlight
                    },
                    data: JSON.stringify({
                        "contactName": name,
                        "email": email,
                        "company": company,
                    }),
                    complete: function (respResult) {
                        if (respResult.status == 200) {
                            $("#user_tel").attr({"data-name": name, "data-email": email,"data-company": company});
                            //$("#user_tel").attr(data-name,name);
                            if (name.length != 0) {
                                $("#my_user_tel").html(name);
                            } else {
                                $("#my_user_tel").html(userTel);
                            }
                            $(".popup-modify").hide().parent(".bg-cover").hide();
                        } else {
                        }
                    }
                });
            },
            cancelValue: '取消',
            cancel: function () {},
        });
        d.showModal();

        var contactName = $("#user_tel").attr("data-name");
        var userTel = $("#user_tel").attr("data-tel");
        var userEmail = $("#user_tel").attr("data-email");
        var userCompany = $("#user_tel").attr("data-company");
        $("#client_tel").val(userTel);
        $("#client_name").val(contactName);
        $("#client_email").val(userEmail);
        $("#client_company").val(userCompany);
    });
}


//验证用户是否登录并获取信息
function validateIsLogin(){
    //判断普通用户是否登录
    $.ajax({
        url: host + "/user/current",
        type: "post",
        dataType: "json",
        xhrFields: {
            withCredentials: true
        },
        beforeSend: function (xhr) {
            xhr.setRequestHeader("Content-Type", "application/json");
        },
        success: function (respResult) {

        },
        complete:function(respResult){
            if(respResult.status == '200'){
                var loginShowRightContentHtml = '<div id="userOpt" class="user-opt">' +
                        '<a href="/message_list.html" class="bell"><i id="xxtx" class=""></i></a><a class="click-show-info">欢迎您，<span id="my_user_tel"></span><em><b></b></em></a>' +
                        '<div class="pullDown-menu">' +
                            '<div class="arrow-up"><div class="arrow-up-block"></div></div>' +
                            '<ul>' +
                                '<li><a href="/message_me.html">开启合作</a></li>' +
                                '<li><a href="/project_assessment.html?title=project">需求评估</a></li>' +
                                '<li><a href=/"my_project.html?title=project" id="my_project">项目管理</a></li>' +
                                '<li><a href="javascript:void(0);" id="user_tel">个人信息</a></li>' +
                                '<li><a href="javascript:void(0);" id="complaints-btn">我要投诉</a></li>' +
                                '<li><a href="javascript:void(0);" id="j-user-logout">退出登录</a></li>' +
                            '</ul>' +
                        '</div>' +
                    '</div>';
                $(".mod-nav #logged").removeClass('hide').html(loginShowRightContentHtml);

                var user = JSON.parse(respResult.responseText);
                var tel = user.tel;
                var contactName = user.contactName;
                var email = user.email;
                var company = user.company;
                $('#myProject').attr("data-user", tel);
                $('#myProject-mp').attr("data-user", tel);
                $("#user_tel").attr({
                    "data-name": contactName,
                    "data-tel": tel,
                    "data-email": email,
                    "data-company": company
                });
                if (contactName != null && contactName != "") {
                    $("#my_user_tel").html(contactName);
                } else {
                    $('#my_user_tel').html(tel);
                }

                $("#contactName").val(user.contactName);
                // 自动填充手机号
                $("#contactTel").val(user.tel);
                // 隐藏验证码框，并自动填一个000000
                $("#code").val("000000");
                $(".j_code_div").hide();

                clickShowRightContent();   //点击显示功能模块
                bindComplaintsBtn();   //绑定投诉按钮
                clickRightExit();  //点击退出
                getListCommentsNotRead(); //未读消息
                updateMyselfInfo();  //点击个人信息

            } else {
                var NoLoginShowRightContentHtml = '<h5 class="message"><a href="/message.html">开启项目</a></h5>';
                $(".mod-nav #notlogged").removeClass('hide');
            }
        }
    });

    // 判断渠道商是否登陆
    $.ajax({
        url: host + "/channel/user/current",
        type: "post",
        dataType: "json",
        xhrFields: {
            withCredentials: true
        },
        beforeSend: function (xhr) {
            xhr.setRequestHeader("Content-Type", "application/json");
        },
        complete: function (respResult) {
            if (respResult.status == 200) {
                var user = JSON.parse(respResult.responseText);
                var name ;
                if(user.contactTel){
                    name = user.contactTel;
                } else {
                    name = user.contactName;
                }
                $('#cooperate').attr("data-user", name);
            }
        }
    });
}
